package etnorservice.etnor_service.service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/04/15/13:52
 **/


import etnorservice.etnor_service.domain.po.LoginAndRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.Map;

@Service
public class EmailService {

    private static final Logger log = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${mail.from.address}")
    private String fromAddress;

    @Value("${mail.from.name}")
    private String fromName;

    /**
     * 发送状态更新通知邮件
     */
    public void sendStatusUpdateEmail(String to, String subject, Map<String, Object> templateVariables) {
        try {
            // 使用Thymeleaf渲染模板
            Context context = new Context();
            templateVariables.forEach(context::setVariable);
            String emailContent = templateEngine.process("mail/status-update", context);

            // 发送邮件
            sendHtmlEmail(to, subject, emailContent);
            log.info("状态更新邮件发送成功: {}", to);
        } catch (Exception e) {
            log.error("状态更新邮件发送失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 发送回复通知邮件
     */
    public void sendReplyEmail(String to, String subject, Map<String, Object> templateVariables) {
        try {
            // 使用Thymeleaf渲染模板
            Context context = new Context();
            templateVariables.forEach(context::setVariable);
            String emailContent = templateEngine.process("mail/reply-notification", context);

            // 发送邮件
            sendHtmlEmail(to, subject, emailContent);
            log.info("回复通知邮件发送成功: {}", to);
        } catch (Exception e) {
            log.error("回复通知邮件发送失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 发送HTML邮件的通用方法
     */
    private void sendHtmlEmail(String to, String subject, String htmlContent) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(fromAddress, fromName);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true);

        mailSender.send(message);
    }

    /**
     * 发送宣传邮件
     */
    public void sendPromotionEmail(String to, String subject) {
        try {
            // 使用Thymeleaf渲染模板
            Context context = new Context();
            // 提取用户名作为个性化内容
            String username = to.contains("@") ? to.split("@")[0] : to;
            context.setVariable("recipientName", username);

            // 使用模板生成邮件内容
            String emailContent = templateEngine.process("mail/promotion", context);

            // 发送邮件
            sendHtmlEmail(to, subject, emailContent);
            log.info("宣传邮件发送成功: {}", to);
        } catch (Exception e) {
            log.error("宣传邮件发送失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送宣传邮件失败", e);
        }
    }


    /**
     * 发送注册成功邮件
     *
     * @param user 注册成功的用户信息
     * @throws MessagingException 邮件发送异常
     */
    public void sendRegistrationSuccessEmail(LoginAndRegister user) throws MessagingException {
        // 准备上下文
        Context context = new Context();
        context.setVariable("username", user.getUsername());
        context.setVariable("account", user.getAccount());
        context.setVariable("email", user.getEmail());
        context.setVariable("currentYear", LocalDate.now().getYear());

        // 生成邮件内容
        String content = templateEngine.process("mail/registration-success", context);

        // 创建邮件消息
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom("support@etnor.xyz");
        helper.setTo(user.getEmail());
        helper.setSubject("E特尔诺 - 注册成功通知");
        helper.setText(content, true);

        // 发送邮件
        mailSender.send(message);
    }



}